package org.flint.data.structure.uf.impl;

import com.google.common.base.Preconditions;
import org.flint.data.structure.uf.UnionFind;

/**
 * @author flint92
 */
public class QuickUnion3 implements UnionFind {

    private int[] parent;

    /**
     * rank[i]存储的是以i为根的集合所表示数的层数
     */
    private int[] rank;

    public QuickUnion3(int size) {

        parent = new int[size];
        rank = new int[size];

        for (int i = 0; i < size; i++) {
            parent[i] = i;
            rank[i] = 1;
        }
    }

    @Override
    public boolean isConnected(int p, int q) {
        return find(p) == find(q);
    }

    @Override
    public void union(int p, int q) {
        int pRoot = find(p);
        int qRoot = find(q);

        if (pRoot == qRoot) {
            return;
        }

        if (rank[pRoot] < rank[qRoot]) {
            parent[pRoot] = qRoot;
        } else if (rank[qRoot] < rank[pRoot]){
            parent[qRoot] = pRoot;
        } else {
            parent[qRoot] = pRoot;
            rank[pRoot] += 1;
        }
    }

    @Override
    public int getSize() {
        return parent.length;
    }

    private int find(int p) {
        Preconditions.checkElementIndex(p, getSize());
        // 当p = parent[p]时 p是根节点
        while (p != parent[p]) {
            p = parent[p];
        }
        return p;
    }
}
